﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


namespace Utils
{
    public class SQLInjectionHelper
    {
        /// <summary>
        /// 获取Post的数据
        /// </summary>
        public static bool ValidUrlData(string request)
        {
            bool result = false;
            //获取Post的数据
            if (request == "POST")
            {
                //for (int i = 0; i < HttpContext.Current.Request.Form.Count; i++)
                //{
                //    result = ValidData(HttpContext.Current.Request.Form[i].ToString());
                //    if (result)
                //    {
                //        break;
                //    }
                //}
            }
            //获取QueryString中的数据
            else
            {
                for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
                {
                    result = ValidData(HttpContext.Current.Request.QueryString[i].ToString());
                    if (result)
                    {
                        break;
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 验证是否存在注入代码
        /// </summary>
        /// <param name="inputData">输入字符</param>
        private static bool ValidData(string inputData)
        {
            //验证inputData是否包含恶意集合
            if (Regex.IsMatch(inputData, GetRegexString()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 获取正则表达式
        /// </summary>
        private static string GetRegexString()
        {
            //构造SQL的注入关键字符
            string[] strBadChar = {"and "
            ,"exec "  ,"insert "  ,"select " ,"delete ","update "
            ,"drop ","\'"               
            ,"xp_cmdshell"  ,"net localgroup administrators"};
            //构造正则表达式
            string str_Regex = ".*(";
            for (int i = 0; i < strBadChar.Length - 1; i++)
            {
                str_Regex += strBadChar[i] + "|";
            }
            str_Regex += strBadChar[strBadChar.Length - 1] + ").*";
            return str_Regex;
        }


    }
}
